/*
 * Copyright (C) Cátedra SAES-UMU 2011 <pedromateo@um.es>
 *
 * Android HCI Extractor is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Android HCI Extractor is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.mmi.android.instrumentation.utils;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AdapterView;

/**
 * Iterator that allows you to iterate over the elements
 * compounding an Android GUI.
 * 
 * @author pedro mateo (pedromateo@um.es)
 *
 */
public class UiTraverser implements java.util.Iterator<View> {
	private static final String TAG = "UiTraverser";

	public UiTraverser(View v)
	{
		nodes_ = new java.util.Stack<View>();
		if (v != null)
		{
			nodes_.push(v);
		}
	}

	public boolean hasNext()
	{
		return !nodes_.empty();
	}


	public View next()
	{
		View v = null;

		//if remaining nodes
		if (hasNext())
		{
			//return the last element
			v = nodes_.pop();
			assert(v != null);
			//if it is a container, add its children to the stack
			if (v instanceof ViewGroup ||
					v instanceof AdapterView)
			{
				ViewGroup vg = (ViewGroup)v;
				for (int i = 0; i < vg.getChildCount(); i++)
				{
					assert(vg.getChildAt(i) != null);
					nodes_.push(vg.getChildAt(i));
				}				
			}
		}

		//return result
		return v;
	}

	public void remove() 
	{
		//not supported
	}

	/**
	 * Internal method to get the top parent of a View
	 * @param v The reference View
	 * @return The top parent
	 */
	public static View getTopParent(View v)
	{
		View result = v;
		ViewParent vp = v.getParent();
		while (vp != null)
		{
			//Log.d(TAG,"Parent :: " + vp.toString());
			if (vp instanceof View)
			{
				result = (View)vp;
				Log.d(TAG,"  :: is View");
			}
			vp = vp.getParent();
		}

		return result;
	}

	private
	java.util.Stack<View> nodes_;
}
